﻿using System;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using S3.Biz;
using S3.Common;
using S3.DataModel;

namespace S3
{
    public partial class ManageUsers : S3FormBase
    {
        public ManageUsers()
        {
            InitializeComponent();

            LoadRoles();
            LoadAllUsers();
        }

        #region Private Methods

       

        private void LoadRoles()
        {
            comboRole.Items.Clear();
            comboRole.Items.Add(UserRoleValue.Text[UserRole.Staff]);
            comboRole.Items.Add(UserRoleValue.Text[UserRole.Admin]);
            comboRole.SelectedIndex = 0;
        }

        private void LoadAllUsers()
        {
            var manager = new UserManager();
            gridUser.DataSource = manager.GetAll();
        }

        /// <summary>
        /// Close form if click ESC
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        private void LoadUserData(string userId)
        {
            using (var userMgr = new UserManager())
            {
                User userData = userMgr.GetOne(userId);
                if (userData != null)
                {
                    txtAccountName.Text = userData.UserID;
                    txtPassword.Text = userData.Password;
                    comboRole.SelectedItem = userData.Role.ToLower();
                }
            }
        }

        #region Event Handlers

        private PopupProgress _popupProgress;

        public override void DoSaveData()
        {

            lblErrorUserName.Text = "";
            lblErrorPassword.Text = "";

            string userName = txtAccountName.Text.Trim();
            if (userName == string.Empty)
            {
                lblErrorUserName.Text = "Hãy gõ tên đăng nhập.";
                txtAccountName.Focus();
                return;
            }

            string password = txtPassword.Text.Trim();
            if (password == string.Empty)
            {
                lblErrorPassword.Text = "Hãy gõ mật khẩu.";
                txtPassword.Focus();
                return;
            }

            if (password.Length < 6)
            {
                lblErrorPassword.Text = "Mật khẩu phải có độ dài tối thiểu 6 kí tự.";
                txtPassword.Focus();
                return;
            }

            using (var manager = new UserManager())
            {
                var user = new User { UserID = userName, Password = Utils.Encrypt(password), Role = comboRole.Text };

                bool isSuccess = manager.Add(user, btnCancel.Visible);

                if (isSuccess)
                {
                    XtraMessageBox.Show("Thêm nhân viên thành công.");
                    LoadAllUsers();
                    txtAccountName.Text = string.Empty;
                    txtPassword.Text = string.Empty;
                }
                else
                {
                    XtraMessageBox.Show("Có lỗi xảy ra trong quá trình thêm nhân viên.");
                }
            }
            if (btnCancel.Visible)
            {
                btnCancel.Visible = false;
                btnAdd.Text = "Thêm";
                txtAccountName.Enabled = true;
            }
            
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            _popupProgress = new PopupProgress { FormOwner = this, Action = UserAction.Save};
            _popupProgress.ShowDialog();
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (gridView1.SelectedRowsCount > 0)
            {
                string userId = Convert.ToString(gridView1.GetRowCellValue(gridView1.GetSelectedRows()[0], "UserID"));
                LoadUserData(userId);
                txtAccountName.Enabled = false;
                btnCancel.Visible = true;
                btnAdd.Text = "Thay đổi";
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            txtAccountName.Text = string.Empty;
            txtPassword.Text = string.Empty;
            comboRole.SelectedIndex = 0;
            btnCancel.Visible = false;
            txtAccountName.Enabled = true;
        }

        #endregion

        #region ProcessCmdKey

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            try
            {
                if (msg.WParam.ToInt32() == (int) Keys.Escape)
                {
                    Close();
                }
                else
                {
                    return base.ProcessCmdKey(ref msg, keyData);
                }
            }
            catch (Exception Ex)
            {
                XtraMessageBox.Show("Key Overrided Events Error:" + Ex.Message);
            }

            return base.ProcessCmdKey(ref msg, keyData);
        }

        #endregion

        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (gridView1.SelectedRowsCount > 0 && e.KeyData == Keys.Delete)
            {
                int[] rowSelectedIndexs = gridView1.GetSelectedRows();
                DialogResult confirm = XtraMessageBox.Show("Bạn muốn xóa account này?", "Chú ý", MessageBoxButtons.YesNo);
                if (confirm == DialogResult.Yes)
                {
                    foreach (int index in rowSelectedIndexs)
                    {
                        string userName = "";
                        userName = gridView1.GetRowCellValue(index, "UserID") + "";
                        if (userName.ToLower() == "admin")
                        {
                            XtraMessageBox.Show("Không được xóa account này.");                           
                            return;
                        }

                        if (!string.IsNullOrEmpty(userName))
                        {
                            using (var manager = new UserManager())
                            {
                                manager.Delete(userName);
                                LoadAllUsers(); 
                                XtraMessageBox.Show("Đã xóa nhân viên " + userName);
                            }
                        }
                        else
                        {                           
                            return;
                        }
                    }
                }
            }
        }

        private void ManageUsers_Load(object sender, EventArgs e)
        {

        }
        #endregion
    }

    
}